#coding=utf8
from google.appengine.api import users
import os
import htmlentitydefs
import re
isdevelopment = os.environ.get('SERVER_SOFTWARE','').startswith('Development')

def update_user_varible(d):
	path = os.environ.get('PATH_INFO','/')
	if os.environ.get('QUERY_STRING',''):
		path+="?"
		path+=os.environ['QUERY_STRING']
	user = users.get_current_user()
	d['islogined'] = user!=None
	if user:
		d['login_username'] = user.email()
	d['logout_url'] = users.create_logout_url('/')
	d['login_url'] = users.create_login_url(path)

def unescape(text):
   """Removes HTML or XML character references 
      and entities from a text string.
      keep &amp;, &gt;, &lt; in the source code.
   from Fredrik Lundh
   http://effbot.org/zone/re-sub.htm#unescape-html
   """
   def fixup(m):
      text = m.group(0)
      if text[:2] == "&#":
         # character reference
         try:
            if text[:3] == "&#x":
               return unichr(int(text[3:-1], 16))
            else:
               return unichr(int(text[2:-1]))
         except ValueError:
            #print "erreur de valeur"
            pass
      else:
         # named entity
         try:
            if text[1:-1] == "amp":
               text = u"&"
            elif text[1:-1] == "gt":
               text = u">"
            elif text[1:-1] == "lt":
               text = u"<"
            else:
               print text[1:-1]
               text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
         except KeyError:
            #print "keyerror"
            pass
      return text # leave as is
   return re.sub("&#?\w+;", fixup, text)
